package com.pdstudio.photos;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.pdstudio.app.Application;
import com.pdstudio.util.NetUtil;
import com.pdstudio.util.SharePreferenceUtil;
import com.pdstudio.weather.R;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/*
 * 上传图片到服务器*/
public class UploadPicActivity extends Activity {

	private static final int NONE = 0;
	private static final int PHOTO_GRAPH = 1;// 拍照
	private static final int PHOTO_ZOOM = 2; // 缩放
	private static final int PHOTO_RESOULT = 3;// 结果
	private static final String IMAGE_UNSPECIFIED = "image/*";

	private Handler mHandler;

	Bundle bundle;// 上个activity传来的图片

	private ImageView showPic;
	private Button btn_up, btn_over;// 上传跟上传完成按钮
	private ProgressBar pb;
	private int picMax = 0;// 图片的流长度

	Bitmap photo;
	ByteArrayOutputStream stream = null;

	private View customLiveIndexTitleView;
	private TextView txtTitle;
	private ImageView ivBack;

	private String actionUrl;
	
	private SharePreferenceUtil mSpUtil;
	private Application mApplication;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photo_uploadfile_main);
		actionUrl = getResources().getString(R.string.upload_photo);

		mApplication = Application.getInstance();
		mSpUtil = mApplication.getSharePreferenceUtil();

		LinearLayout layout = (LinearLayout) findViewById(R.id.photo_uploadfile_main);
		int resId = mApplication.getApplicationBackground(mSpUtil
				.getWeatherStatus());
		layout.setBackground(getResources().getDrawable(resId));

		customLiveIndexTitleView = findViewById(R.id.phto_upload_title);
		txtTitle = (TextView) customLiveIndexTitleView
				.findViewById(R.id.title2_text_nav);
		txtTitle.setText("图片上传");
		ivBack = (ImageView) findViewById(R.id.title2_back);
		ivBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				UploadPicActivity.this.finish();

			}

		});


		showPic = (ImageView) findViewById(R.id.upload_show_pic);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				dm.widthPixels, dm.widthPixels);
		showPic.setLayoutParams(lp);

		btn_up = (Button) findViewById(R.id.btn_upload_begin);
		btn_up.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				btn_up.setVisibility(View.GONE);
				pb.setVisibility(View.VISIBLE);
				// TODO Auto-generated method stub
				Thread thread = new Thread(new Runnable() {
					public void run() {
						// uploadFile();
						uploadFile1();
						// uploadFile2();

						/*
						 * List<NameValuePair> params=new
						 * ArrayList<NameValuePair>(); NameValuePair nv=new
						 * BasicNameValuePair("imgFile","xxxx.jpg");
						 * NameValuePair nv1=new
						 * BasicNameValuePair("description","sdafasdf");
						 * NameValuePair nv2=new
						 * BasicNameValuePair("address","address");
						 * NameValuePair nv3=new
						 * BasicNameValuePair("userName","user");
						 * params.add(nv); params.add(nv1); params.add(nv2);
						 * params.add(nv3); uploadFile3(params);
						 */
					}
				});
				thread.start();
			}

		});
		btn_over = (Button) findViewById(R.id.btn_upload_end);
		btn_over.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(UploadPicActivity.this,
						PhotoGalleryActivity.class);
				startActivity(intent);
				finish();
			}
		});

		btn_up.setClickable(true);
		btn_over.setClickable(false);
		pb = (ProgressBar) findViewById(R.id.pb_upload_photo);
		pb.setIndeterminate(false);
		try {
			/* 获取Intent中的Bundle对象 */
			bundle = this.getIntent().getExtras();
			photo = bundle.getParcelable("data");
			stream = new ByteArrayOutputStream();
			photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0-100)压缩文件
			// 此处可以把Bitmap保存到sd卡中，具体请看：http://www.cnblogs.com/linjiqin/archive/2011/12/28/2304940.html
			showPic.setImageBitmap(photo); // 把图片显示在ImageView控件上

		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, "获取图片失败，请重新选择！", Toast.LENGTH_SHORT).show();
		}

		if (stream != null) {
			// final float max=stream.size();
			// picMax=(int)max;
			// pb.setMax((int)max);

			// 定义一个Handler
			mHandler = new Handler() {
				public void handleMessage(Message msg) {
					switch (msg.what) {
					case 1:
						Thread.currentThread().interrupt();
						btn_up.setClickable(false);
						btn_over.setClickable(true);
						// pb.setProgress((int)max);
						pb.setVisibility(View.GONE);
						// btn_over.setVisibility(View.VISIBLE);
						Toast.makeText(UploadPicActivity.this, "文件上传完成", Toast.LENGTH_SHORT).show();
						Intent intent = new Intent(UploadPicActivity.this,
								PhotoGalleryActivity.class);
						startActivity(intent);
						finish();
						break;
					default:
						break;
					}
				}
			};
		}
	}

	/* 上传文件至Server的方法 */
	private void uploadFile() {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		try {
			actionUrl = actionUrl
					+ "?appkeys="+Application.getInstance().getSharePreferenceUtil().getAuthCode()+"&desc=hello&username=admin&uploadTime=20141010";
			URL url = new URL(actionUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			/* 允许Input、Output，不使用Cache */
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设置传送的method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			/* 添加参数 */

			/* 设置DataOutputStream */
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; "
					+ "name=\"file1\";filename=\"" + "文件名称" + "\"" + end);
			ds.writeBytes(end);
			/* 取得文件的FileInputStream */
			FileInputStream fStream = new FileInputStream(
					Environment.getExternalStorageDirectory() + "/temp.jpg");
			/* pb长度 */
			pb.setMax(fStream.available());
			/* 设置每次写入1024bytes */
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			int pbsize = 0;
			/* 从文件读取数据至缓冲区 */
			while ((length = fStream.read(buffer)) != -1) {
				/* 将资料写入DataOutputStream中 */
				ds.write(buffer, 0, length);
				try {
					pbsize++;
					pb.setProgress(length * pbsize);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			/* close streams */
			fStream.close();
			ds.flush();
			/* 取得Response内容 */
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			/* 将Response显示于Dialog */
			pb.setProgress(fStream.available());
			Toast.makeText(this, "上传成功" + b.toString().trim(), 1000);
			/* 关闭DataOutputStream */
			ds.close();
			mHandler.sendEmptyMessage(1);
		} catch (Exception e) {
			Toast.makeText(this, "上传失败" + e, Toast.LENGTH_SHORT).show();
		}
	}

	private void uploadFile1() {
		try {
			actionUrl = actionUrl + "?appkeys="+Application.getInstance().getSharePreferenceUtil().getAuthCode();
			// actionUrl = "http://192.168.0.102:8018/partymember/addphoto";
			URL url = new URL(actionUrl);
			HttpClient httpclient = new DefaultHttpClient();
			// 设置通信协议版本
			httpclient.getParams().setParameter(
					CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

			// File path= Environment.getExternalStorageDirectory(); //取得SD卡的路径

			// String pathToOurFile = path.getPath()+File.separator+"ak.txt";
			// //uploadfile
			// String urlServer = "http://192.168.1.88/test/upload.php";

			HttpPost httppost = new HttpPost(actionUrl);
			/* 设置每次写入1024bytes */
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];

			File file = new File(Environment.getExternalStorageDirectory()
					,"temp.jpg");
			try {
				BufferedOutputStream bos = null;
				FileOutputStream fos = new FileOutputStream(file);
				bos = new BufferedOutputStream(fos);
				bos.write(stream.toByteArray());
				bos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			/* pb长度 */
			// pb.setMax((int) file.length());

			MultipartEntity mpEntity = new MultipartEntity(); // 文件传输
			ContentBody cbFile = new FileBody(file);
			mpEntity.addPart("imgFile", cbFile); // <input type="file"
													// name="userfile" /> 对应的
			ContentBody des = new StringBody("无标题",Charset.forName(HTTP.UTF_8));
			
			ContentBody add = new StringBody(Application.getInstance().getCurSimpleCity().cityCode,Charset.forName(HTTP.UTF_8));
			ContentBody user = new StringBody(Application.getInstance().getCurSimpleCity().cityCode,Charset.forName(HTTP.UTF_8));
			mpEntity.addPart("description", des);
			mpEntity.addPart("address", add);
			mpEntity.addPart("userName", user);

			httppost.setEntity(mpEntity);
			System.out
					.println("executing request " + httppost.getRequestLine());

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity resEntity = response.getEntity();

			System.out.println(response.getStatusLine());// 通信Ok
			String json = "";
			String path = "";
			if (resEntity != null) {
				// System.out.println(EntityUtils.toString(resEntity,"utf-8"));
				json = EntityUtils.toString(resEntity, "utf-8");
				JSONObject p = null;
				try {
					p = new JSONObject(json);
					// path=(String) p.get("path");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (resEntity != null) {
				resEntity.consumeContent();
			}

			httpclient.getConnectionManager().shutdown();
			mHandler.sendEmptyMessage(1);
		} catch (Exception e) {
			Toast.makeText(this, "上传失败" + e, Toast.LENGTH_SHORT).show();
		}
	}

	private void uploadFile2() {
		try {
			actionUrl = actionUrl
					+ "?appkeys="+Application.getInstance().getSharePreferenceUtil().getAuthCode()+"&desc=hello&username=admin&uploadTime=20141010";
			actionUrl = "http://192.168.0.102:8018/partymember/addphoto";
			URL url = new URL(actionUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			/* 允许Input、Output，不使用Cache */
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设置传送的method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type", "application/octet-stream");
			/* 添加参数 */

			/* 设置DataOutputStream */
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
			/* 取得文件的FileInputStream */
			FileInputStream fStream = new FileInputStream(
					Environment.getExternalStorageDirectory() + "/temp.jpg");
			/* pb长度 */
			int pbsize = 0;
			pbsize = fStream.available();
			pb.setMax(pbsize);
			/* 设置每次写入1024bytes */
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			/* 从文件读取数据至缓冲区 */
			while ((length = fStream.read(buffer)) != -1) {
				/* 将资料写入DataOutputStream中 */
				ds.write(buffer, 0, length);
				try {
					pbsize++;
					pb.setProgress(length * pbsize);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			/* close streams */
			fStream.close();
			ds.flush();
			/* 取得Response内容 */
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			JSONObject p = null;
			try {
				p = new JSONObject(b.toString());
				// path=(String) p.get("path");
			} catch (Exception e) {
				e.printStackTrace();
			}
			/* 将Response显示于Dialog */
			pb.setProgress(pbsize);
			// Toast.makeText(this, "上传成功" + b.toString().trim(), 1000);
			/* 关闭DataOutputStream */
			ds.close();
			mHandler.sendEmptyMessage(1);
		} catch (Exception e) {
			e.printStackTrace();
			// Toast.makeText(this, "上传失败" + e, 1000);
		}
	}

	private void uploadFile3(List<NameValuePair> params) {
		actionUrl = actionUrl
				+ "?appkeys="+Application.getInstance().getSharePreferenceUtil().getAuthCode()+"&desc=hello&username=admin&uploadTime=20141010";
		if (NetUtil.getNetworkState(getApplicationContext()) != NetUtil.NETWORN_NONE) {
			try {
				HttpPost hp = new HttpPost(actionUrl);
				hp.addHeader("Content-Type", "multipart/form-data");
				// 设置字符集
				// HttpEntity entity = new
				// UrlEncodedFormEntity(params,HTTP.UTF_8);
				// 设置参数实体
				// hp.setEntity(entity);
				// 获取HttpClient对象
				HttpClient httpClient = new DefaultHttpClient();
				// 连接超时
				httpClient.getParams().setParameter(
						CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
				// 请求超时
				httpClient.getParams().setParameter(
						CoreConnectionPNames.SO_TIMEOUT, 30000);

				// 获取HttpResponse实例
				HttpResponse httpResp = httpClient.execute(hp);
				// 判断是够请求成功
				if (httpResp.getStatusLine().getStatusCode() == 200) {
					// 获取返回的数据
					String result = EntityUtils.toString(httpResp.getEntity(),
							"UTF-8");
					// Log.i("HttpPost", "HttpPost方式请求成功，返回数据如下：");
					// Log.i("result", result);
				} else {
					// Log.i("HttpPost", "HttpPost方式请求失败");
				}

			} catch (Exception e) {
			}
		}
	}
}
